package cn.itcast.bos.web.action;

import cn.itcast.bos.domain.base.Courier;
import cn.itcast.bos.domain.base.Standard;
import cn.itcast.bos.service.CourierService;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;

import javax.persistence.criteria.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Think on 2017/9/16.
 *
 */
@Controller
@ParentPackage("json-default")
@Namespace("/")
@Scope("prototype")
public class CourierAction extends ActionSupport implements ModelDriven<Courier> {
    private Courier courier = new Courier();
    @Override
    public Courier getModel() {
        return courier;
    }
    @Autowired
    private CourierService courierService;



    @Action(value = "courier_save",results = {@Result(name = SUCCESS,location = "./pages/base/courier.html",type = "redirect"),
                                                @Result(name = ERROR,type = "redirect",location = "unauthorized.html")})
    public String save(){
        try {
            courierService.save(courier);
            return SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return ERROR;
        }
    }

    //获取页面提交的简单属性
    private int page;
    private int rows;

    public void setPage(int page) {
        this.page = page;
    }

    public void setRows(int rows) {
        this.rows = rows;
    }

    @Action(value="courier_pageQuery",results={@Result(name="success",type="json")})
    public String pageQuery(){
        // 无查询条件
//		Pageable pageable = new PageRequest(page-1, rows);
//		Page<Courier> page = courierService.findPageQuery(pageable);
//		Map<String, Object> map = new HashMap<String,Object>();
//		map.put("total", page.getTotalElements());
//		map.put("rows", page.getContent());
//		ServletActionContext.getContext().getValueStack().push(map);

        // 有条件的查询
        Pageable pageable = new PageRequest(page-1, rows);
        // 组织查询条件
        Specification<Courier> specification = new Specification<Courier>() {

            // 返回的Predicate对象封装结果集
            @Override
            public Predicate toPredicate(Root<Courier> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                /**
                 * 传递：
                 * 		Root<Courier> root：（连接语句的时候需要字段，获取字段的名称）代表Criteria查询的根对象，Criteria查询的查询根定义了实体类型，能为将来导航获得想要的结果，它与SQL查询中的FROM子句类似
                 * 		CriteriaQuery<?> query： （简单的查询可以使用CriteriaQuery）代表一个specific的顶层查询对象，它包含着查询的各个部分，比如：select 、from、where、group by、order by等
                 * 		CriteriaBuilder cb：（复杂的查询可以使用CriteriaBuilder构建）用来构建CritiaQuery的构建器对象
                 * 返回：Predicate：封装查询条件
                 */
                Predicate predicate = null;
                // 用来封装查询条件（页面传递4个查询条件 ）
                List<Predicate> list = new ArrayList<Predicate>();
                // 工号（组织查询条件）
                if(StringUtils.isNotBlank(courier.getCourierNum())){
                    Predicate p = cb.equal(root.get("courierNum").as(String.class), courier.getCourierNum());// courierNum = ?
                    list.add(p);
                }
                // 所属单位
                if(StringUtils.isNotBlank(courier.getCompany())){
                    Predicate p = cb.like(root.get("company").as(String.class), "%"+courier.getCompany()+"%");// company like ?
                    list.add(p);
                }
                // 取派员类型
                if(StringUtils.isNotBlank(courier.getType())){
                    Predicate p = cb.like(root.get("type").as(String.class), "%"+courier.getType()+"%");// type like ?
                    list.add(p);
                }

                // 收派标准
                if(courier.getStandard()!=null && courier.getStandard().getId()!=null){
                    // 联合查询
                    // 表示创建一个联合查询的对象
                    Join<Courier, Standard> join = root.join("standard",JoinType.INNER);
                    Predicate p = cb.equal(join.get("id").as(Integer.class), courier.getStandard().getId());// standart.id = ?
                    list.add(p);
                }

                // 方案一：表示存在查询条件
				if(list!=null && list.size()>0){
					Predicate [] p = new Predicate[list.size()];
					predicate = cb.and(list.toArray(p));
				}

				return predicate;
                // 方案二：表示存在查询条件（使用query）
               /* if(list!=null && list.size()>0){
                    Predicate [] p = new Predicate[list.size()];
                    query.where(list.toArray(p));
                }
                // 按照id降序排列
                query.orderBy(cb.desc(root.get("id").as(Integer.class)));

                return query.getRestriction();// 返回结果*/
            }
        };
        Page<Courier> page = courierService.findPageQueryCondition(specification, pageable);
        Map<String, Object> map = new HashMap<String,Object>();
        map.put("total", page.getTotalElements());
        map.put("rows", page.getContent());
        ServletActionContext.getContext().getValueStack().push(map);
        return SUCCESS;
    }

    private String ids;

    public void setIds(String ids) {
        this.ids = ids;
    }

    @Action(value = "courier_deleteCourier",results = {@Result(name = SUCCESS,type = "redirect",location = "./pages/base/courier.html")})
    public String deleteCourier(){
        //按","分割ids
        String[] idArray = ids.split(",");
        courierService.deleteCourierById(idArray);
        return SUCCESS;
    }

    @Action(value = "courier_restoreCourier",results = {@Result(name = SUCCESS,type = "redirect",location = "./pages/base/courier.html")})
    public String restoreCourier(){
        //按","分割ids
        String[] idArray = ids.split(",");
        courierService.restoreCourierById(idArray);
        return SUCCESS;
    }

    /**
     * 查询没有被关联的快递员信息,返回页面显示(下拉框...)
     */
    @Action(value = "courier_findnoassociation",results = {@Result(name = SUCCESS,type = "json")})
    public String findnoassociation(){
        List<Courier> list = courierService.findnoassociation();
        ServletActionContext.getContext().getValueStack().push(list);
        return SUCCESS;
    }

    /**
     * 查询定区关联的快递员,显示
     */
    // 定区ID
    private String fixedAreaId;

    public void setFixedAreaId(String fixedAreaId) {
        this.fixedAreaId = fixedAreaId;
    }

    // 查询当前定区ID，对应的快递员的集合
    @Action(value="courier_findAssociationCourier",results={@Result(name="success",type="json")})
    public String findAssociationCourier(){
        List<Courier> list = courierService.findAssociationCourier(fixedAreaId);
        ServletActionContext.getContext().getValueStack().push(list);
        return SUCCESS;
    }

}
